﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using CH.Easy.DbProvider.Common;
using CH.Easy.DbProvider.Mapping;
namespace CH.Easy.DbProvider.ExpressionExtend
{
    public class FromExpression : Expression
    {

        public SelectExpression Select { get; set; }
        public string Alias { get; set; }
        public string Name { get; set; }
        public string PrimaryKey { get; set; }
        public Type TableType { get; set; }
        public FromExpression(Expression expression)
        {
            if (expression == null) 
            {
                Select = null;
                return;
            }
               

            this.Select = expression as SelectExpression;
            if (this.Select.Expression.NodeType == ExpressionType.Constant)
            {
                ConstantExpression c = this.Select.Expression as ConstantExpression;
                TableType = DbProviderHelper.GetElementType(c.Type);
            }
            else if(this.Select.Expression.NodeType == ExpressionType.Call)
            {
                TableType = DbProviderHelper.GetElementType(this.Select.Expression.Type);
            }
            else
            {
                TableType = DbProviderHelper.GetElementType(((LambdaExpression)((UnaryExpression)this.Select.Column.Expression).Operand).Body.Type);
            }
            this.Alias = "T" + TableType.GetHashCode();
            this.Name = TableType.Name;
            this.PrimaryKey = "ID";

            var attributes = TableType.GetCustomAttributes(typeof(TableMappingAttribute), true);
            if (attributes != null && attributes.Count() > 0)
            {
                foreach (var attribute in attributes)
                {
                    TableMappingAttribute a = attribute as TableMappingAttribute;
                    if (a != null)
                    {

                        this.Name = a.Name;
                        this.PrimaryKey = a.PrimaryKey;
                    }
                }
            }

        }

        
        public override ExpressionType NodeType
        {
            get
            {
                return (ExpressionType)ExpressionTypeExend.From;
            }
        }

    }
}
